﻿/// ****************************************************************************
/// Author:	        Robin Zhu
/// Create Date:	2013-4-30
/// Purpose: 		类成员访问器定义文件
/// ****************************************************************************
/// Modify By		Date			Remark
/// ****************************************************************************
/// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace RB.DataAccess
{
    /// <summary>
    /// 成员读取访问接口定义
    /// </summary>
    public interface IMemberGetter
    {
        /// <summary>
        /// Get the member value of an object.
        /// </summary>
        /// <param name="instance">The object to get the member value from.</param>
        /// <param name="memberName">The member name, could be the name of a property of field. Must be public member.</param>
        /// <returns>The member value</returns>
        object GetValue(object instance);
    }

    /// <summary>
    /// 成员设置访问接口定义
    /// </summary>
    public interface IMemberSetter
    {
        /// <summary>
        /// Set the member value of an object.
        /// </summary>
        /// <param name="instance">The object to get the member value from.</param>
        /// <param name="memberName">The member name, could be the name of a property of field. Must be public member.</param>
        /// <param name="newValue">The new value of the property for the object instance.</param>
        void SetValue(object instance, object newValue);
    }

    /// <summary>
    /// 成员属性设置访问类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="P"></typeparam>
    public class PropertySetter<T, P> : IMemberSetter
    {
        private Action<T, P> SetValueDelegate;

        public PropertySetter(PropertyInfo propertyInfo)
        {
            if (propertyInfo != null)
            {
                SetValueDelegate = (Action<T, P>)Delegate.CreateDelegate(typeof(Action<T, P>), propertyInfo.GetSetMethod());
            }
        }

        public void SetValue(object instance, object newValue)
        {
            SetValueDelegate((T)instance, (P)newValue);
        }
    }

    /// <summary>
    /// 成员属性读取访问类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="P"></typeparam>
    public class PropertyGetter<T, P> : IMemberGetter
    {
        private Func<T, P> GetValueDelegate;

        public PropertyGetter(PropertyInfo propertyInfo)
        {
            if (propertyInfo != null)
            {
                GetValueDelegate = (Func<T, P>)Delegate.CreateDelegate(typeof(Func<T, P>), propertyInfo.GetGetMethod());
            }
        }

        public object GetValue(object instance)
        {
            return GetValueDelegate((T)instance);
        }
    }
}
